package com.cloudOffice.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cloudOffice.model.process.ProcessTemplate;
import com.cloudOffice.result.Result;
import com.cloudOffice.service.OaProcessTemplateService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 审批模板
 */
@Slf4j
@Tag(name = "审批模板管理")
@RestController("OaProcessTemplateController")
@RequestMapping("/admin/process/processTemplate")
public class OaProcessTemplateController {
	
	@Resource
	private OaProcessTemplateService processTemplateService;
	
	
	//分页查询审批模板
	@Operation(summary = "获取分页审批模板数据")
	@GetMapping("{page}/{limit}")
	public Result<IPage<ProcessTemplate>> index(@PathVariable Long page,
	                                            @PathVariable Long limit) {
		log.info("分页查询审批模板：page: {}, limit: {}", page, limit);
		Page<ProcessTemplate> pageParam = new Page<>(page, limit);
		return Result.success(processTemplateService.selectPageProcessTempate(pageParam));
	}
	
	// 获取审批模板
	@Operation(summary = "获取审批模板")
	@GetMapping("get/{id}")
	public Result<ProcessTemplate> get(@PathVariable Long id) {
		log.info("获取审批模板：id: {}", id);
		return Result.success(processTemplateService.getById(id));
	}
	
	// 新增审批模板
	@Operation(summary = "新增审批模板")
	@PostMapping("save")
	public Result<?> save(@RequestBody ProcessTemplate processTemplate) {
		log.info("新增审批模板：processTemplate: {}", processTemplate);
		processTemplateService.save(processTemplate);
		return Result.success();
	}
	
	// 修改审批模板
	@Operation(summary = "修改审批模板")
	@PutMapping("update")
	public Result<?> updateById(@RequestBody ProcessTemplate processTemplate) {
		log.info("修改审批模板：processTemplate: {}", processTemplate);
		processTemplateService.updateById(processTemplate);
		return Result.success();
	}
	
	// 删除审批模板
	@Operation(summary = "删除审批模板")
	@DeleteMapping("remove/{id}")
	public Result<?> remove(@PathVariable Long id) {
		log.info("删除审批模板：id: {}", id);
		processTemplateService.removeById(id);
		return Result.success();
	}
	
	@Operation(summary = "上传流程定义")
	@PostMapping("/uploadProcessDefinition")
	public Result<?> uploadProcessDefinition(MultipartFile file) throws FileNotFoundException {
		//获取classes目录位置
		String path = new File(ResourceUtils.getURL("classpath:")
				.getPath()).getAbsolutePath();
		//设置上传文件夹
		File tempFile = new File(path + "/processes/");
		if (!tempFile.exists()) {
			tempFile.mkdirs();
		}
		//创建空文件，实现文件写入
		String filename = file.getOriginalFilename();
		File zipFile = new File(path + "/processes/" + filename);
		
		//保存文件
		try {
			file.transferTo(zipFile);
		} catch (IOException e) {
			return Result.fail();
		}
		
		Map<String, Object> map = new HashMap<>();
		//根据上传地址后续部署流程定义，文件名称为流程定义的默认key
		map.put("processDefinitionPath", "processes/" + filename);
		if (filename != null) {
			map.put("processDefinitionKey", filename.substring(0, filename.lastIndexOf(".")));
		}
		return Result.success(map);
	}
	
	//部署流程定义（发布）
	@Operation(summary = "发布部署流程")
	@GetMapping("/publish/{id}")
	public Result<?> publish(@PathVariable Long id) {
		log.info("发布部署流程：id: {}", id);
		//修改模板发布状态 1 已经发布
		processTemplateService.publish(id);
		return Result.success();
	}
	
}

